<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="keywords" content="Hexo Theme Keep">
    <meta name="description" content="Hexo Theme Keep">
    <meta name="author" content="cm_westwood">
    
    <title>
        
            第2周 |
        
        西木同学的代码训练 2022
    </title>
    
<link rel="stylesheet" href="/code_training_2022/css/style.css">

    <link rel="shortcut icon" href="">
    
<link rel="stylesheet" href="/code_training_2022/css/font-awesome.min.css">

    <script id="hexo-configurations">
    let KEEP = window.KEEP || {};
    KEEP.hexo_config = {"hostname":"cm_westwood.gitee.io","root":"/code_training_2022/","language":"en","path":"search.json"};
    KEEP.theme_config = {"toc":{"enable":true,"number":true,"expand_all":true,"init_open":true},"style":{"primary_color":"#0066CC","avatar":"","favicon":"","article_img_align":"left","left_side_width":"260px","content_max_width":"920px","hover":{"shadow":false,"scale":false},"first_screen":{"enable":true,"background_img":"https://xpoet.cn/images/bg.svg","description":"Keep writing and Keep loving."},"scroll":{"progress_bar":{"enable":true},"percent":{"enable":true}}},"local_search":{"enable":true,"preload":false},"code_copy":{"enable":true,"style":"default"},"pjax":{"enable":false},"lazyload":{"enable":true},"version":"3.4.5"};
    KEEP.language_ago = {"second":"%s seconds ago","minute":"%s minutes ago","hour":"%s hours ago","day":"%s days ago","week":"%s weeks ago","month":"%s months ago","year":"%s years ago"};
  </script>
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
<div class="progress-bar-container">
    
        <span class="scroll-progress-bar"></span>
    

    
</div>


<main class="page-container">

    

    <div class="page-main-content">

        <div class="page-main-content-top">
            <header class="header-wrapper">

    <div class="header-content">
        <div class="left">
            
            <a class="logo-title" href="/">
                西木同学的代码训练 2022
            </a>
        </div>

        <div class="right">
            <div class="pc">
                <ul class="menu-list">
                    
                        <li class="menu-item">
                            <a class=""
                               href="/code_training_2022/"
                            >
                                HOME
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/code_training_2022/archives"
                            >
                                ARCHIVES
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/code_training_2022/tags"
                            >
                                TAGS
                            </a>
                        </li>
                    
                    
                        <li class="menu-item search search-popup-trigger">
                            <i class="fas fa-search"></i>
                        </li>
                    
                </ul>
            </div>
            <div class="mobile">
                
                    <div class="icon-item search search-popup-trigger"><i class="fas fa-search"></i></div>
                
                <div class="icon-item menu-bar">
                    <div class="menu-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="header-drawer">
        <ul class="drawer-menu-list">
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/code_training_2022/">HOME</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/code_training_2022/archives">ARCHIVES</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/code_training_2022/tags">TAGS</a>
                </li>
            
        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="page-main-content-middle">

            <div class="main-content">

                
                    <div class="fade-in-down-animation">
    <div class="article-content-container">

        <div class="article-title">
            <span class="title-hover-animation">第2周</span>
        </div>

        
            <div class="article-header">
                <div class="avatar">
                    <img src="">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">cm_westwood</span>
                        
                            <span class="author-label">Lv2</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fas fa-edit"></i>&nbsp;
        <span class="pc">2022-06-19 13:44:07</span>
        <span class="mobile">2022-06-19 13:44</span>
    </span>
    
    
        <span class="article-tags article-meta-item">
            <i class="fas fa-tags"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/code_training_2022/tags/Python/">Python</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    

    
    
    
    
</div>

                    </div>
                </div>
            </div>
        

        <div class="article-content markdown-body">
            <p>Python LRU 缓存，Python 包读取静态资源，Python handle <a target="_blank" rel="noopener" href="https://docs.python.org/3/library/warnings.html#module-warnings"><code>warnings</code></a> — Warning control</p>
<span id="more"></span>

<h1 id="Python-LRU-缓存"><a href="#Python-LRU-缓存" class="headerlink" title="Python LRU 缓存"></a>Python LRU 缓存</h1><p>为了实现这个需求，Python 3.2 + 中给我们提供了一个机制，可以很方便地实现，而不需要你去写这样的逻辑代码。<br>这个机制实现于 functool 模块中的 lru_cache 装饰器。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@functools.lru_cache(<span class="params">maxsize=<span class="literal">None</span>, typed=<span class="literal">False</span></span>)</span></span><br></pre></td></tr></table></figure>
<p>参数解读：</p>
<ul>
<li>maxsize：最多可以缓存多少个此函数的调用结果，如果为None，则无限制，设置为 2 的幂时，性能最佳</li>
<li>typed：若为 True，则不同参数类型的调用将分别缓存。</li>
</ul>
<h2 id="Python-LRU-cache-with-time-to-live"><a href="#Python-LRU-cache-with-time-to-live" class="headerlink" title="Python LRU cache with time-to-live"></a>Python LRU cache with time-to-live</h2><p>利用 python 中 lru_cache 缓存的是函数的调用参数的特性，使用整除量化时间，就可以让 LRU 过期</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> lru_cache</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@lru_cache()</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">my_expensive_function</span>(<span class="params">a, b, ttl_hash=<span class="literal">None</span></span>):</span><br><span class="line">    <span class="keyword">del</span> ttl_hash  <span class="comment"># to emphasize we don&#x27;t use it and to shut pylint up</span></span><br><span class="line">    <span class="keyword">return</span> a + b  <span class="comment"># horrible CPU load...</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">get_ttl_hash</span>(<span class="params">seconds=<span class="number">3600</span></span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return the same value withing `seconds` time period&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">round</span>(time.time() / seconds)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># somewhere in your code...</span></span><br><span class="line">res = my_expensive_function(<span class="number">2</span>, <span class="number">2</span>, ttl_hash=get_ttl_hash())</span><br><span class="line"><span class="comment"># cache will be updated once in an hour</span></span><br></pre></td></tr></table></figure>

<ol>
<li><a class="link"   target="_blank" rel="noopener" href="https://stackoverflow.com/questions/31771286/python-in-memory-cache-with-time-to-live" >Python in-memory cache with time to live<i class="fas fa-external-link-alt"></i></a></li>
</ol>
<h1 id="Python-包读取静态资源"><a href="#Python-包读取静态资源" class="headerlink" title="Python 包读取静态资源"></a>Python 包读取静态资源</h1><p>1.1 硬编码文件路径</p>
<p>使用最直接的方法， open函数，传入data.txt文件的路径，即可访问文件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># test.py</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&#x27;package/data.txt&#x27;</span>, <span class="string">&#x27;r&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    text = f.read()</span><br><span class="line">    <span class="built_in">print</span>(text)</span><br></pre></td></tr></table></figure>

<p>1.2 使用<code>__file__</code>定位，使用绝对路径</p>
<p>一种更加优雅的方式，是使用文件的__file__属性，定位到当前的路径， 结合pathlib，使用绝对路径访问目标文件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pathlib</span><br><span class="line">PATH = pathlib.Path(__file__)</span><br><span class="line"> </span><br><span class="line">data_file = PATH.parent / <span class="string">&#x27;package&#x27;</span> /<span class="string">&#x27;data.txt&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(data_file.read_text())</span><br></pre></td></tr></table></figure>

<p>1.3 setuptools.pkg_resources</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pkg_resources</span><br><span class="line"></span><br><span class="line"><span class="comment"># Could be any dot-separated package/module name or a &quot;Requirement&quot;</span></span><br><span class="line">resource_package = __name__</span><br><span class="line">resource_path = <span class="string">&#x27;/&#x27;</span>.join((<span class="string">&#x27;templates&#x27;</span>, <span class="string">&#x27;temp_file&#x27;</span>))  <span class="comment"># Do not use os.path.join()</span></span><br><span class="line">template = pkg_resources.resource_string(resource_package, resource_path)</span><br><span class="line"><span class="comment"># or for a file-like stream:</span></span><br><span class="line">template = pkg_resources.resource_stream(resource_package, resource_path)</span><br></pre></td></tr></table></figure>

<p>1.4 importlib.resources </p>
<p>Python 3.7 引入标准库中的新模块 importlib.resources</p>
<p>这个模块使得 Python 的导入系统提供了访问包内的资源的功能。<strong>如果能够导入一个包，那么就能够访问那个包里面的资源</strong>。资源可以以二进制或文本模式方式被打开或读取。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> importlib.resources <span class="keyword">as</span> res</span><br><span class="line"><span class="keyword">import</span> package</span><br><span class="line"> </span><br><span class="line">text = res.read_text(package, <span class="string">&#x27;data.txt&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>, errors=<span class="string">&#x27;strict&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(text)</span><br></pre></td></tr></table></figure>

<ol>
<li><a class="link"   target="_blank" rel="noopener" href="https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package" >https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package<i class="fas fa-external-link-alt"></i></a></li>
<li><a class="link"   target="_blank" rel="noopener" href="https://blog.csdn.net/be5yond/article/details/120062721" >https://blog.csdn.net/be5yond/article/details/120062721<i class="fas fa-external-link-alt"></i></a></li>
</ol>
<h1 id="Python-handle-warnings-—-Warning-control"><a href="#Python-handle-warnings-—-Warning-control" class="headerlink" title="Python handle warnings — Warning control"></a>Python handle <a target="_blank" rel="noopener" href="https://docs.python.org/3/library/warnings.html#module-warnings"><code>warnings</code></a> — Warning control</h1><p>在和用户交互的过程中，函数里仅仅抛出异常是不够的，还需要抛出一些警告信息，但是不中断程序的进行</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> warnings</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">fxn</span>():</span><br><span class="line">    warnings.warn(<span class="string">&quot;deprecated&quot;</span>, DeprecationWarning)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> warnings.catch_warnings(record=<span class="literal">True</span>) <span class="keyword">as</span> w:</span><br><span class="line">    <span class="comment"># Cause all warnings to always be triggered.</span></span><br><span class="line">    warnings.simplefilter(<span class="string">&quot;always&quot;</span>)</span><br><span class="line">    <span class="comment"># Trigger a warning.</span></span><br><span class="line">    fxn()</span><br><span class="line">    <span class="comment"># Verify some things</span></span><br><span class="line">    <span class="keyword">assert</span> <span class="built_in">len</span>(w) == <span class="number">1</span></span><br><span class="line">    <span class="keyword">assert</span> <span class="built_in">issubclass</span>(w[-<span class="number">1</span>].category, DeprecationWarning)</span><br><span class="line">    <span class="keyword">assert</span> <span class="string">&quot;deprecated&quot;</span> <span class="keyword">in</span> <span class="built_in">str</span>(w[-<span class="number">1</span>].message)</span><br></pre></td></tr></table></figure>

<p><a class="link"   target="_blank" rel="noopener" href="https://docs.python.org/3/library/warnings.html" >https://docs.python.org/3/library/warnings.html<i class="fas fa-external-link-alt"></i></a></p>

        </div>

        

        
            <ul class="post-tags-box">
                
                    <li class="tag-item">
                        <a href="/code_training_2022/tags/Python/">#Python</a>&nbsp;
                    </li>
                
            </ul>
        

        
            <div class="article-nav">
                
                    <div class="article-prev">
                        <a class="prev"
                           rel="prev"
                           href="/code_training_2022/2022/07/09/%E7%AC%AC3%E5%91%A8/"
                        >
                            <span class="left arrow-icon flex-center">
                              <i class="fas fa-chevron-left"></i>
                            </span>
                            <span class="title flex-center">
                                <span class="post-nav-title-item">第3周</span>
                                <span class="post-nav-item">Prev posts</span>
                            </span>
                        </a>
                    </div>
                
                
                    <div class="article-next">
                        <a class="next"
                           rel="next"
                           href="/code_training_2022/2022/06/19/%E7%AC%AC1%E5%91%A8/"
                        >
                            <span class="title flex-center">
                                <span class="post-nav-title-item">第1周</span>
                                <span class="post-nav-item">Next posts</span>
                            </span>
                            <span class="right arrow-icon flex-center">
                              <i class="fas fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        

        
    </div>
</div>


                
            </div>

        </div>

        <div class="page-main-content-bottom">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info info-item">
            &copy;
            
              <span>2022</span>
              -
            
            2023&nbsp;<i class="fas fa-heart icon-animate"></i>&nbsp;<a href="/">cm_westwood</a>
        </div>
        
        <div class="theme-info info-item">
            Powered by <a target="_blank" href="https://hexo.io">Hexo</a>&nbsp;|&nbsp;Theme&nbsp;<a class="theme-version" target="_blank" href="https://github.com/XPoet/hexo-theme-keep">Keep v3.4.5</a>
        </div>
        
        
    </div>
</footer>

        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="tools-list">
        <!-- TOC aside toggle -->
        
            <li class="tools-item page-aside-toggle">
                <i class="fas fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
    </ul>
</div>

        </div>
    

    <div class="right-bottom-side-tools">
        <div class="side-tools-container">
    <ul class="side-tools-list">
        <li class="tools-item tool-font-adjust-plus flex-center">
            <i class="fas fa-search-plus"></i>
        </li>

        <li class="tools-item tool-font-adjust-minus flex-center">
            <i class="fas fa-search-minus"></i>
        </li>

        <li class="tools-item tool-expand-width flex-center">
            <i class="fas fa-arrows-alt-h"></i>
        </li>

        <li class="tools-item tool-dark-light-toggle flex-center">
            <i class="fas fa-moon"></i>
        </li>

        <!-- rss -->
        

        

        <li class="tools-item tool-scroll-to-bottom flex-center">
            <i class="fas fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="exposed-tools-list">
        <li class="tools-item tool-toggle-show flex-center">
            <i class="fas fa-cog fa-spin"></i>
        </li>
        
            <li class="tools-item tool-scroll-to-top flex-center">
                <i class="arrow-up fas fa-arrow-up"></i>
                <span class="percent"></span>
            </li>
        
    </ul>
</div>

    </div>

    
        <aside class="page-aside">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Python-LRU-%E7%BC%93%E5%AD%98"><span class="nav-number">1.</span> <span class="nav-text">Python LRU 缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-LRU-cache-with-time-to-live"><span class="nav-number">1.1.</span> <span class="nav-text">Python LRU cache with time-to-live</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Python-%E5%8C%85%E8%AF%BB%E5%8F%96%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90"><span class="nav-number">2.</span> <span class="nav-text">Python 包读取静态资源</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Python-handle-warnings-%E2%80%94-Warning-control"><span class="nav-number">3.</span> <span class="nav-text">Python handle warnings — Warning control</span></a></li></ol>
    </div>
</div>
        </aside>
    

    <div class="image-viewer-container">
    <img src="">
</div>


    
        <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
          <span class="search-input-field-pre">
            <i class="fas fa-keyboard"></i>
          </span>
            <div class="search-input-container">
                <input autocomplete="off"
                       autocorrect="off"
                       autocapitalize="off"
                       placeholder="Search..."
                       spellcheck="false"
                       type="search"
                       class="search-input"
                >
            </div>
            <span class="popup-btn-close">
                <i class="fas fa-times"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fas fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>

    

</main>




<script src="/code_training_2022/js/utils.js"></script>

<script src="/code_training_2022/js/main.js"></script>

<script src="/code_training_2022/js/header-shrink.js"></script>

<script src="/code_training_2022/js/back2top.js"></script>

<script src="/code_training_2022/js/dark-light-toggle.js"></script>



    
<script src="/code_training_2022/js/local-search.js"></script>




    
<script src="/code_training_2022/js/code-copy.js"></script>




    
<script src="/code_training_2022/js/lazyload.js"></script>



<div class="post-scripts">
    
        
<script src="/code_training_2022/js/left-side-toggle.js"></script>

<script src="/code_training_2022/js/libs/anime.min.js"></script>

<script src="/code_training_2022/js/toc.js"></script>

    
</div>



</body>
</html>
